# -*- coding: utf-8 -*-

import datetime
import json
import os
import sys
from random import randint

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")

from common.pay.db import create_pay, update_pay_ext
from common.pay.model import PAY_STATUS, PAY_TYPE
from common.transaction.db import add_pay_success_transaction
from common.pay.handler import pay_after_recharge


def main(pay_type, user_id, amount):
    if pay_type not in PAY_TYPE.value_list:
        print('invalid pay_type')
        exit()
    channel = 'agent_wechat'
    if pay_type in [PAY_TYPE.UNIONAGENCY, PAY_TYPE.UNIONAGENCY_V2_ALI, PAY_TYPE.UNIONAGENCY_V2_BANKCARD,
                    PAY_TYPE.UNIONAGENCY_V2_WX]:
        channel = 'unionagency'
    if pay_type in [PAY_TYPE.JUSTPAY_WX, PAY_TYPE.JUSTPAY_ALI, PAY_TYPE.JUSTPAY_UNION, PAY_TYPE.JUSTPAY_QQ,
                    PAY_TYPE.JUSTPAY_JD, PAY_TYPE.JUSTPAY_TEST]:
        channel = 'justpay'

    pay = create_pay(user_id, pay_type)
    pay.status = PAY_STATUS.SUBMIT
    pay.save()
    pay_id = pay.id
    total_fee = amount
    extend = {
        'title': u'充值',
        'ext': {
            'trade_status': 1,
            'trade_no': 'test_%s' % randint(1000000, 9999999),
            'total_fee': total_fee
        }
    }
    update_pay_ext(pay_id, extend['ext'])
    res = add_pay_success_transaction(user_id, pay_id, total_fee, extend)
    if res:
        print 'start tracking'
        file_path = '/var/log/bigbang/track.json'
        f = open(file_path, 'a')
        data = ({
            'type': 'recharge',
            'user_id': int(user_id),
            'price': total_fee,
            'channel': channel,
            "@timestamp": datetime.datetime.now().isoformat(),
        })
        data = json.dumps(data)
        f.write(data)
        f.write('\n')
        f.close()
        try:
            pay_after_recharge(pay)
        except Exception as e:
            print 'pay_after_recharge of pay[%s] exception.(%s)' % (pay.id, e)


if __name__ == "__main__":
    main(int(sys.argv[1]), sys.argv[2], float(sys.argv[3]))
